package com.qf.controller;

import com.qf.utils.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author bss
 * @version V1.0
 * @Project maven
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/10/10 17:44
 */
@RestController
public class UserController {


    @RequestMapping("/doLogin")
    public Result login(String username, String password, boolean rememberMe){

        try {
            Subject subject = SecurityUtils.getSubject();

            Md5Hash md5Hash = new Md5Hash(username,password,1024);
            UsernamePasswordToken token = new UsernamePasswordToken(username, md5Hash.toString());

            if (rememberMe){
                token.setRememberMe(true);
            }

            subject.login(token);

            System.out.println(subject.hasRole("管理员"));
            System.out.println(subject.isPermitted("sys:user:add"));

        } catch (UnknownAccountException e) {
            e.printStackTrace();
            return Result.error("未知的用户");
        }catch (LockedAccountException e){
            e.printStackTrace();
            return Result.error("账户已锁定");
        }catch (CredentialsException e){
            e.printStackTrace();
            return Result.error("密码错误");
        }catch (RuntimeException e){
            e.printStackTrace();
            return Result.error("用户名为空");
        }

        return Result.ok("登陆成功");
    }



    @RequestMapping("/logout")
    public ModelAndView logout(ModelAndView mav){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        mav.setViewName("redirect:/login.html");
        return mav;
    }


    @RequiresRoles("管理员")
    @RequiresPermissions(value = {"sys:user:add","sys:role:add"},logical = Logical.OR)
    @RequestMapping("/add")
    public Result add(){
        System.out.println("add");
        return null;
    }

//    @RequiresRoles("开发工程师")
    @RequiresPermissions("sys:user:edit")
    @RequestMapping("/edit")
    public Result edit(){
        System.out.println("编辑");
        return null;
    }

    @RequiresGuest
    @RequestMapping("/del")
    public Result del(){
        System.out.println("删除");
        return null;
    }
}
